# Name: JoinLastOfWildGrid.py - MCBS 10/18/2014
# Description: Joins wild area codes on Last of the Wild maps to grid

# import system module
import arcpy
from arcpy import env
#from arcpy.sa import *


# Set workspace environment:
#env.workspace = "CanasatData.gdb"
env.workspace = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\MunicBasedData\CanasatData.gdb"
env.overwriteOutput = True
#arcpy.CheckOutExtension("Spatial")

# Folder to store tables:
PathForTables = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\MunicBasedData\Tables"

# Input grid:
GridName      = "G1kmMiR"
# Output grids name:
OutName       = "G1kmMiRLastOfWild"

fieldmappings   = arcpy.FieldMappings()
fieldmappings.addTable("LastOfWild")
# Remove unused info from LastOfWild:
fieldmappings.removeFieldMap(14)
fieldmappings.removeFieldMap(13)
fieldmappings.removeFieldMap(12)
fieldmappings.removeFieldMap(11)
fieldmappings.removeFieldMap(10)
fieldmappings.removeFieldMap(9)
fieldmappings.removeFieldMap(7)
fieldmappings.removeFieldMap(6)
fieldmappings.removeFieldMap(5)
fieldmappings.removeFieldMap(4)
fieldmappings.removeFieldMap(2)
fieldmappings.removeFieldMap(1)
fieldmappings.removeFieldMap(0)
# Add Grid mapping
fieldmappings.addTable(GridName)

arcpy.SpatialJoin_analysis(GridName, "LastOfWild", OutName,
	                           "JOIN_ONE_TO_MANY", "KEEP_ALL", fieldmappings,
							   "COMPLETELY_WITHIN", "", "")
print "Joining attributes from " + JoinClass + " to grid."
print "New Grid file containing attributes created: " + OutName
print " "
# Save .dbf tables in specified folder
TableName    = OutName + ".dbf"
arcpy.TableToTable_conversion(OutName, PathForTables, TableName)






